<template>
  <!-- // 这是头部   -->
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输商品名称" v-model="search.name">
      </el-input>
      <el-select @change='handleFilter' style="width: 140px" class="filter-item" v-model="search.category_id">
        <el-option label="全部" value=""></el-option>
        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.category_id"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary"  plain v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" v-waves type="primary" v-roles="'editProduct'"  icon="el-icon-edit">添加</el-button>
      <!-- <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"  v-roles="'export_product'" @click="handleDownload">导出</el-button> -->
      <el-button class="filter-item" type="primary"  v-waves icon="el-icon-download"  @click="copyProduct" v-roles="'copyProduct'">复制商品</el-button>
    </div>
    <!-- // 这是内容 -->
    <tree-table :data="listData" :evalFunc="funcTree"  :row-class-name="tableRowClassName"  :expandAll="true" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row stripe>
      <el-table-column width="110px" align="center" label="排序">
        <template slot-scope="scope">
          <span  v-if="!scope.row.product_id">
              <el-input @blur="handleSortBlur(scope.row)" style="width: 80px;" class="filter-item" placeholder="排序" v-model="scope.row.sort"></el-input>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="图片" width="80">
        <template slot-scope="scope">
           <span><img :src="scope.row.thumb" style="width:60px;height:80px" onerror='this.src="http://wx.qlogo.cn/mmopen/C2rEUskXQiblFYMUl9O0G05Q6pKibg7V1WpHX6CIQaic824apriabJw4r6EWxziaSt5BATrlbx1GVzwW2qjUCqtYpDvIJLjKgP1ug/0"' /></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标题">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="进价">
        <template slot-scope="scope">
          <span>{{scope.row.xprice}}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" label="库存">
        <template slot-scope="scope">
          <span>{{scope.row.kucun}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="总销量">
        <template slot-scope="scope">
          <span>{{scope.row.all_sales}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="平台售价" width="100">
        <template slot-scope="scope">
          <span v-if="cellShow"><el-input @change="handleBlur(scope.row, 'price')" v-model="scope.row.price" type='number' min="0.00" step="0.01" ></el-input></span>
          <span v-else @click="cellShow=true" style="color:#F56C6C">{{scope.row.price}}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" label="商家售价" width="100">
        <template slot-scope="scope">
          <span v-if="cellShow"><el-input @change="handleBlur(scope.row, 'reprice')" v-model="scope.row.reseller_price" type='number' min="0.00" step="0.01" ></el-input></span>
          <span v-else @click="cellShow=true" style="color:#FF00FF">{{scope.row.reseller_price}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型" width="150">
        <template slot-scope="scope">
            <el-tag>{{scope.row.category_name}}</el-tag>&nbsp;
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{scope.row.status | statusName}}</el-tag>
        </template>
      </el-table-column>
      <!-- //这里是操作   -->
      <el-table-column align="center" label="操作" width="270" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status==0" size="mini" @click="handleModifyStatus(scope.row,'1')">上架</el-button>
          <el-button v-if="scope.row.status==1 || scope.row.status==2 " size="mini" @click="handleModifyStatus(scope.row,'0')">下架</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handlDel(scope.row)" v-roles="'deleteProduct'">删除</el-button>
          <el-button v-if="typeof (scope.row.children) !=='undefined'" type="primary"  size="mini" @click="handleCreate(scope.row,'addSpace')">添加规格</el-button>
        </template>
      </el-table-column>
    </tree-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- // 这里是弹出按钮 -->

    <!-- // 搜索复制商品窗口  -->
    <copy-product :visible.sync="editVisible" @refresh='isrefresh'></copy-product>  
    <!--编辑窗口  END -->

    <!--可自定义按钮的样式、show/hide临界点、返回的位置  -->
    <!--如需文字提示，可在外部添加element的<el-tooltip></el-tooltip>元素  -->
    <el-tooltip placement="top" content="回到顶部">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>
  </div>
</template>


<script>
import waves from '@/directive/waves' // 水波纹指令
import BackToTop from '@/components/BackToTop' // 回到顶部
import treeTable from '@/components/TreeTable'
import treeToArray from './customEval'
import copyProduct from './copyProduct'
import * as api from '@/api/main-api' // API
import { mapGetters } from 'vuex'

export default {
  name: 'ProductList',
  directives: {
    waves
  },
  components: { BackToTop, treeTable, copyProduct },
  data() {
    return {
      // 回到顶部样式
      myBackToTopStyle: {
        right: '50px',
        bottom: '50px',
        width: '40px',
        height: '40px',
        'z-index': '9999',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
        background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
      },
      options: [],
      listData: [],
      listLoading: false,
      search: {
        category_id: undefined,
        name: '',
        sort: 100
      },
      listQuery: {
        page: 1,
        pagesize: 10,
        unit_id: 0
      },
      total: 0,
      funcTree: treeToArray,
      downloadLoading: false,
      editVisible: false,
      cellShow: false
    }
  },

  // 初始化数据
  created() {
    this.listQuery.unit_id = this.outlet_id
    if (Object.keys(this.set_page_params).length > 0) {
      this.listQuery = this.set_page_params
    }
    setTimeout(() => {
      this.fetchData()
    }, 100)
    this.typeOption()
    this.$store.dispatch('setPageParams', {}) // 回归原来的状态
  },

  computed: {
    ...mapGetters([
      'outlet_id',
      'set_page_params'
    ])
  },

  // 装换属性
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    },
    statusName(status) {
      return (status === '1') ? '上架中' : (status === '0') ? '已下架' : '库存紧张'
    }
  },
  methods: {
    // table颜色
    tableRowClassName({ row, rowIndex }) {
      if (row.kucun <= 2) {
        return ' warning-row' // return 'success-row';
      } else {
        return ''
      }
    },

    // 排序
    handleSortBlur(row) {
      var data = {
        id: row.id,
        unit_id: this.outlet_id, // 添加属性
        field: 'sort', // 修改单个字段
        types: 'products',
        status: row.sort // 值,
      }
      this.postFieldStatus(data, row)
      row.sort = data.status
    },

    // 改变总状态02版(统一)
    postFieldStatus(data, row) {
      api.stateApi(data).then(response => {
        if (response.data.code === 0) {
          this.$root.message('操作成功', 'success')
        }
      })
    },

    // 商家价格修改
    handleBlur(row, type) {
      var data = {
        id: row.id,
        change_status: 1
      }
      if (type === 'price') {
        data.price = row.price
      } else {
        data.reseller_price = row.reseller_price
      }
      if (typeof (row.product_id) === 'undefined') {
        data.unit_id = this.outlet_id // 添加属性
      } else {
        data.product_id = row.product_id // 添加属性
      }
      this.postData(data, row)
      this.cellShow = false
    },

    // 修改状态
    handleModifyStatus(row, status) {
      var data = {
        status: status,
        id: row.id,
        change_status: 1
      }
      if (typeof (row.product_id) === 'undefined') {
        data.unit_id = this.outlet_id // 添加属性
      } else {
        data.product_id = row.product_id // 添加属性
      }
      this.postData(data, row)
      row.status = data.status
    },

    // 编辑
    handleUpdate(row) {
      // 存在 vuex
      delete row.children
      delete row.parent
      this.$store.dispatch('setGoodInfo', row)
      // 返回原来的界面保存参数
      this.$store.dispatch('setPageParams', Object.assign(this.listQuery, this.search))
      this.$nextTick(() => {
        this.$router.push({
          path: '/product/edit-product',
          name: 'editProduct',
          query: { es: 'edit' }
        })
      })
    },

    // 添加商品/规格
    handleCreate(row, type) {
      if (type === 'addSpace') {
        delete row.children
        this.$store.dispatch('setGoodInfo', row)
        var query = { es: 'add', 'sp': 'space' }
        // 返回原来的界面保存参数
        this.$store.dispatch('setPageParams', Object.assign(this.listQuery, this.search))
      } else {
        query = { es: 'add' }
      }
      this.$nextTick(() => {
        this.$router.push({
          path: '/product/edit-product',
          name: 'editProduct',
          query: query
        })
      })
    },

    // 删除操作
    handlDel(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      }).catch(() => {
        this.$root.message('已取消删除', 'info')
      })
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      // 复制一个对象<br>var obj = { a: 1 ,b:2};
      this.fetchData()
    },
    // 翻页
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.fetchData()
    },
    // 跳页
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },

    // 获取数据
    fetchData() {
      this.listLoading = true
      this.listQuery = Object.assign(this.listQuery, this.search)
      return new Promise((resolve, reject) => {
        api.goodsIndexApi(this.listQuery).then(response => {
          if (response.data.code === 0) {
            this.listData = response.data.data
            this.total = parseInt(response.data.total)
          }
          this.listLoading = false
        })
      })
    },

    // 获取类别数据
    typeOption() {
      return new Promise((resolve, reject) => {
        api.categoryApi(this.listQuery).then(response => {
          if (response.data.code === 0) {
            this.options = response.data.data
          }
        })
      })
    },

    // 商品提交数据
    postData(data, row) {
      api.editProductApi(data, row).then(response => {
        if (response.data.data === true || response.data.code === 0) {
          this.$root.message('操作成功', 'success')
        }
      })
    },

    // 删除数据
    deleteData(row) {
      var data = {
        id: row.id
      }
      if (typeof (row.product_id) !== 'undefined') {
        data.product_id = row.product_id // 添加属性
      } else {
        data.unit_id = this.outlet_id // 添加属性
      }

      api.delProductApi(data, row).then(response => {
        if (response.data.code === 0) {
          this.$root.message('删除成功', 'success')
          if (typeof (row.product_id) === 'undefined') {
            const index = this.listData.indexOf(row)
            this.listData.splice(index, 1)
            this.total = this.total - 1
          } else {
            for (const v of this.listData) {
              if (v.id === row.product_id) {
                const index = v.children.indexOf(row)
                v.children.splice(index, 1)
                break
              }
            }
          }
        }
      })
    },

    // 复制商品 2018-07-27
    copyProduct() {
      this.editVisible = !this.editVisible
    },

    // 子窗口关闭,刷新数据
    isrefresh(data) {
      this.fetchData()
    }

  },

  // 监事事件
  watch: {
    outlet_id(id) {
      this.$nextTick(() => {
        setTimeout(() => {
          this.listQuery.unit_id = id
          this.fetchData() // 商品
          this.typeOption() // 类别
        }, 20)
      })
    }
  }
}
</script>


<style>
  .el-table .warning-row {
    background: rgb(241, 216, 193);
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
